package yxy.game.pm2.proto;

import java.io.File;
import java.io.IOException;

import com.alibaba.fastjson.JSONArray;

public class CommandGeneratorJs extends CommandGenerator {

	private String className = "Noname";
	private String packageName = null;

	public CommandGeneratorJs(boolean trusted, String packageName, String className) {
		super(trusted);
		this.packageName = packageName;
		this.className = className;
	}

	@Override
	@Deprecated
	public void generate(JSONArray json, File output, String encoding) throws IOException {
		super.generate(json, output, encoding);
	}

	public void generate(JSONArray json, String src, String encoding) throws IOException {
		String filename = this.className + ".js";
		String path = src + "/" + this.packageName.replaceAll("\\.", "/") + "/output";
		File output = new File(path + "/" + filename);
		this.generate(json, output, encoding);
	}

	@Override
	protected String assembleField(int level, String parent, String type, String name, String comment, String value, String desc, String messagefile) {
		String indentation = this.indent(level);
		StringBuffer buffer = new StringBuffer();

		if (desc != null) {
			buffer.append(String.format("//**** %s *******************************************\r\n\r\n", desc));
		}

		if (value.endsWith("C")) {
			String formatC = "    %s : %s,\r\n\r\n";//
			if (comment != null) {
				buffer.append(String.format("    //%s\r\n", comment));// 注释
			}
			buffer.append(String.format(formatC, name, value));
			return buffer.toString();
		}

		String formatA = "    %sRequest : %s,\r\n";//

		String formatB = "    %sResponse : %s,\r\n\r\n";//

		if (comment != null) {
			buffer.append(String.format("    //%s 请求\r\n", comment));// 注释
		}
		buffer.append(String.format(formatA, name, value));

		if (comment != null) {
			buffer.append(String.format("    //%s 响应\r\n", comment));// 注释
		}
//		String valueB = value.replace('A', 'B');
		String valueB = value.substring(0, value.length() - 1) + "B";
		buffer.append(String.format(formatB, name, valueB));

		return buffer.toString();
	}

	@Override
	protected String assembleHeader(int level, String type, String name, String comment) {
		String indentation = this.indent(level);
		StringBuffer buffer = new StringBuffer();

		if (comment != null) {
			buffer.append(String.format("\r\n%s//%s\r\n", indentation, comment));
		}
		if (level == 0 && type == null) {
			buffer.append("/*\r\n" + //
					" * @Author: 170cm白胖子\r\n" + //
					" */\r\n" + //
					"var Command = {" + //
					"\r\n"); //
		}
		return buffer.toString();
	}

	@Override
	protected String assembleFooter(int level, String type, String name, String comment) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("};");
		return buffer.toString();
	}
}
